package com.sangananitsolution.gogoproject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.sangananitsolution.database.UserInfoCRUD;
import com.sangananitsolution.fragments.MainBackgroundFragment;

public class MainActivity extends Activity {

	// Your Facebook APP ID
	private static String APP_ID = "603493253079688"; // Replace your App ID
														// here
	String emailMianActivity, passwordforasyntask;
	private ProgressDialog progress;
	// Instance of Facebook Class
	private Facebook facebook;
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;
	String isvaliduser;
	String email, password;

	private final String URL = "http://garagesalesagogo.com.au/AuthenticationService.asmx?op=ValidateLogin";
	private final String SOAP_ACTION = "http://tempuri.org/ValidateLogin";
	private String TAG = "PGGURU";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity);
		findViewById(R.id.imgeSignUP);
		findViewById(R.id.imgeLogin);
		findViewById(R.id.imgeSignUPWithFacebook);

	}




	public void SignUp(View view) {
		startActivity(new Intent(this, SignUp.class));

	}

	public void facebooklogin(View view) { 

		facebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(facebook);

		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}

					});
		}

		getProfileInformation();

	}

	private void getProfileInformation() {
		// TODO Auto-generated method stub

		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					JSONObject profile = new JSONObject(json);
					// getting name of the user
					final String name = profile.getString("name");
					// getting email of the user
					final String email = profile.getString("email");

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
					/*	Toast.makeText(getApplicationContext(),
									"Name: " + name + "\nEmail: " + email,
									Toast.LENGTH_LONG).show();*/
						
						
						
						
						startActivity(new Intent(MainActivity.this,MainBackgroundFragment.class));
						
						
						
						
						
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});

	}

	public void loginToapp(View view) {
		EditText email, passsword;

		email = (EditText) findViewById(R.id.etEmialMainActivity);
		emailMianActivity = email.getText().toString();

		passsword = (EditText) findViewById(R.id.etPassMainActivity);
		passwordforasyntask = passsword.getText().toString();

		if (emailMianActivity.length() != 0
				&& emailMianActivity.toString() != "") {
			if (passwordforasyntask.length() != 0
					&& passwordforasyntask.toString() != "") {

				new LoginValidate().execute();

			} else {
				Toast.makeText(getApplicationContext(), "Fill Password",
						Toast.LENGTH_LONG).show();

			}

		}

		else {
			Toast.makeText(getApplicationContext(), "Fill Email Address",
					Toast.LENGTH_LONG).show();

		}
	}

	private class LoginValidate extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			
			SoapObject validateLoginobj = null;
			// Create request

			validateLoginobj = new SoapObject("http://tempuri.org/",
					"ValidateLogin");
			validateLoginobj.addProperty("userName", emailMianActivity);
			validateLoginobj.addProperty("password", passwordforasyntask);

			// Create envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;

			// Set output SOAP object
			envelope.setOutputSoapObject(validateLoginobj);

			envelope.implicitTypes = true;

			// Create HTTP call object
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

			SoapObject validateLoginResponseobj = null;
			SoapObject validateLoginResultobj = null;
			SoapObject locationobj = null;
			SoapObject loginStatusobj = null;

			try {
				// Invole web service
				androidHttpTransport.call(SOAP_ACTION, envelope);
				// Get the response
				validateLoginResponseobj = (SoapObject) envelope.bodyIn;
				validateLoginResultobj = (SoapObject) validateLoginResponseobj
						.getProperty(0);
				loginStatusobj = (SoapObject) validateLoginResultobj
						.getProperty("LoginStatus");
				isvaliduser = loginStatusobj.getPropertyAsString("IsValidUser");
				if (isvaliduser.equalsIgnoreCase("true")) {

					String useremail = validateLoginResultobj
							.getPropertyAsString("EmailAddress");
					String fname = validateLoginResultobj
							.getPropertyAsString("FirstName");

					String lname = validateLoginResultobj
							.getPropertyAsString("LastName");
					String phone = validateLoginResultobj
							.getPropertyAsString("PhoneNumber");

					String country = validateLoginResultobj
							.getPropertyAsString("Country");

					locationobj = (SoapObject) validateLoginResultobj
							.getProperty("Location");
					String longitute = locationobj
							.getPropertyAsString("Longitude");
					String latitute = locationobj
							.getPropertyAsString("Latitude");

					String imageinfo = validateLoginResultobj
							.getPropertyAsString("UserImage");

					String facebookId = validateLoginResultobj
							.getPropertyAsString("FacebookId");

					String statusmsg = loginStatusobj
							.getPropertyAsString("StatusMessage");
					String hashcode = loginStatusobj
							.getPropertyAsString("HashCode");
					String userid = validateLoginResultobj
							.getPropertyAsString("UserId");

					UserInfoCRUD userInfoCRUD = new UserInfoCRUD(
							getApplicationContext());
					userInfoCRUD.insert(useremail, fname, lname, phone,
							country, longitute, latitute, imageinfo,
							facebookId, userid, hashcode, statusmsg, userid);

				} else {

				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;

		}

		@Override
		protected void onPostExecute(String result) {
			

			
			if(progress.isShowing())
			{
				progress.dismiss();
				
			}
			if (isvaliduser.equalsIgnoreCase("true")) {

				startActivity(new Intent(getApplicationContext(),
						MainBackgroundFragment.class));

			} else {

				Toast.makeText(getApplicationContext(),
						"Login Credetial are worng", Toast.LENGTH_LONG).show();

			}

			super.onPostExecute(result);

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = ProgressDialog.show(MainActivity.this, "",
					"Processing...");
			progress.setIndeterminate(true);
			progress.getWindow().setLayout(
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

		}

	}
}
